<template>
  <div class="transfer-list-v3">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <h2>{{ t('transfer.title') }}</h2>
      <div class="header-actions">
        <el-button @click="refreshTransfers" :icon="Refresh">{{ t('transfer.header.refresh') }}</el-button>
        <el-button @click="clearHistory" type="danger" plain>{{ t('transfer.header.clearHistory') }}</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="transfer-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <el-icon class="stat-icon" color="#409eff"><UploadFilled /></el-icon>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.inProgressCount }}</div>
                <div class="stat-label">{{ t('transfer.stats.inProgress') }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <el-icon class="stat-icon" color="#67c23a"><CircleCheckFilled /></el-icon>
              <div class="stat-content">
                <div class="stat-value completed">{{ statistics.completedCount }}</div>
                <div class="stat-label">{{ t('transfer.stats.completed') }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <el-icon class="stat-icon" color="#f56c6c"><CircleCloseFilled /></el-icon>
              <div class="stat-content">
                <div class="stat-value failed">{{ statistics.failedCount }}</div>
                <div class="stat-label">{{ t('transfer.stats.failed') }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <el-icon class="stat-icon" color="#909399"><Histogram /></el-icon>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.totalCount }}</div>
                <div class="stat-label">{{ t('transfer.stats.total') }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 连接状态 -->
    <div class="connection-status">
      <!-- 首次连接中 -->
      <el-alert v-if="connectionState === 'connecting' && reconnectAttempts === 0"
                :title="t('transfer.connection.connecting_title')"
                type="info"
                :closable="false"
                show-icon>
        <template #default>
          {{ t('transfer.connection.connecting_desc') }}
        </template>
      </el-alert>

      <!-- 重连中 -->
      <el-alert v-else-if="connectionState === 'reconnecting'"
                :title="t('transfer.connection.reconnecting_title')"
                type="warning"
                :closable="false"
                show-icon>
        <template #default>
          {{ t('transfer.connection.reconnecting_desc', { attempts: reconnectAttempts }) }}
        </template>
      </el-alert>

      <!-- 连接失败（多次重连后） -->
      <el-alert v-else-if="showConnectionWarning"
                :title="t('transfer.connection.disconnected_title')"
                type="error"
                :closable="false"
                show-icon>
        <template #default>
          {{ t('transfer.connection.disconnected_desc') }}
          <el-button size="small" @click="reconnectSocket">{{ t('transfer.connection.reconnect') }}</el-button>
        </template>
      </el-alert>
    </div>

    <!-- 视图切换器 -->
    <div class="view-switcher">
      <el-segmented v-model="viewMode" :options="viewOptions" size="large" />
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 当前传输 -->
      <div v-if="viewMode === 'current'" class="card-grid-wrapper">
        <!-- 分片上传会话 -->
        <div v-if="fileUpload.getAllSessions().length > 0" class="upload-sessions-section">
          <h3 class="section-title">{{ t('transfer.upload.title') }}</h3>
          <div class="transfer-list">
            <div v-for="session in fileUpload.getAllSessions()" :key="session.uploadId"
                 class="transfer-item" :class="getUploadStatusClass(session.status)">
              <div class="transfer-info">
                <div class="file-info">
                  <el-icon :size="20" class="file-icon"><component :is="getFileIcon(session.fileName)" /></el-icon>
                  <div class="file-details">
                    <div class="file-name" :title="session.fileName">{{ session.fileName }}</div>
                    <div class="file-size">{{ formatFileSize(session.fileSize) }}</div>
                  </div>
                </div>
                <div class="progress-info">
                  <el-progress
                    :percentage="session.progress"
                    :status="getUploadProgressStatus(session.status)"
                    :stroke-width="4"
                  />
                  <div class="transfer-stats">
                    <span class="transferred">{{ formatFileSize(session.uploadedBytes) }} / {{ formatFileSize(session.fileSize) }}</span>
                    <span class="speed">
                      <span v-if="session.speed > 0">{{ fileUpload.formatSpeed(session.speed) }}</span>
                      <span v-else-if="session.status === 'uploading' || session.status === 'preparing'">传输中</span>
                      <span v-else>{{ getUploadStatusText(session.status) }}</span>
                    </span>
                    <span class="chunks">{{ session.uploadedChunks.size }} / {{ session.totalChunks }} 分片</span>
                  </div>
                </div>
              </div>
              <div class="transfer-actions">
                <el-button-group size="small">
                  <el-button
                    @click="pauseUploadSession(session.uploadId)"
                    v-if="session.status === 'uploading'"
                    :icon="VideoPause">
                    {{ t('transfer.current.pause') }}
                  </el-button>
                  <el-button
                    @click="resumeUploadSession(session.uploadId)"
                    v-if="session.status === 'paused'"
                    :icon="VideoPlay">
                    {{ t('transfer.current.resume') }}
                  </el-button>
                  <el-button
                    @click="retryUploadSession(session.uploadId)"
                    v-if="session.status === 'failed'"
                    :icon="RefreshRight">
                    {{ t('transfer.current.retry') }}
                  </el-button>
                  <el-button
                    type="danger"
                    @click="cancelUploadSession(session.uploadId)"
                    :icon="Delete">
                    {{ t('transfer.current.cancel') }}
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 下载会话 -->
        <div v-if="downloadSessions.length > 0" class="download-sessions-section">
          <h3 class="section-title">{{ t('transfer.download.title') }}</h3>
          <div class="transfer-list">
            <div v-for="session in downloadSessions" :key="session.downloadId"
                 class="transfer-item" :class="getDownloadStatusClass(session.status)">
              <div class="transfer-info">
                <div class="file-info">
                  <el-icon :size="20" class="file-icon"><component :is="getFileIcon(session.fileName)" /></el-icon>
                  <div class="file-details">
                    <div class="file-name" :title="session.fileName">{{ session.fileName }}</div>
                    <div class="file-size">
                      <span v-if="session.fileSize > 0">{{ formatFileSize(session.fileSize) }}</span>
                      <span v-else>未知大小</span>
                    </div>
                  </div>
                </div>
                <div class="progress-info">
                  <el-progress
                    :percentage="session.fileSize > 0 ? session.progress : 0"
                    :status="getDownloadProgressStatus(session.status)"
                    :stroke-width="4"
                    :indeterminate="session.fileSize <= 0 && session.status === 'downloading'"
                  />
                  <div class="transfer-stats">
                    <span class="transferred">
                      {{ formatFileSize(session.downloadedBytes) }}
                      <span v-if="session.fileSize > 0"> / {{ formatFileSize(session.fileSize) }}</span>
                    </span>
                    <span class="speed">
                      <span v-if="session.speed > 0">{{ fileDownload.formatSpeed(session.speed) }}</span>
                      <span v-else-if="session.status === 'downloading' || session.status === 'preparing'">下载中</span>
                      <span v-else>{{ getDownloadStatusText(session.status) }}</span>
                    </span>
                  </div>
                </div>
              </div>
              <div class="transfer-actions">
                <el-button-group size="small">
                  <el-button
                    @click="pauseDownloadSession(session.downloadId)"
                    v-if="session.status === 'downloading'"
                    :icon="VideoPause">
                    {{ t('transfer.current.pause') }}
                  </el-button>
                  <el-button
                    @click="resumeDownloadSession(session.downloadId)"
                    v-if="session.status === 'paused'"
                    :icon="VideoPlay">
                    {{ t('transfer.current.resume') }}
                  </el-button>
                  <el-button
                    @click="retryDownloadSession(session.downloadId)"
                    v-if="session.status === 'failed'"
                    :icon="RefreshRight">
                    {{ t('transfer.current.retry') }}
                  </el-button>
                  <el-button
                    type="danger"
                    @click="cancelDownloadSession(session.downloadId)"
                    :icon="Delete">
                    {{ t('transfer.current.cancel') }}
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </div>

        <!-- Socket.IO传输记录 -->
        <div v-if="activeTransfers.length === 0 && fileUpload.getAllSessions().length === 0 && downloadSessions.length === 0" class="empty-state">
          <el-empty :description="t('transfer.current.empty')" />
        </div>
        <div v-if="activeTransfers.length > 0" class="socket-transfers-section">
          <h3 class="section-title">{{ t('transfer.socket.title') }}</h3>
          <div class="transfer-list">
            <div v-for="transfer in activeTransfers" :key="transfer.id" class="transfer-item" :class="getStatusClass(transfer.transferStatus)">
              <div class="transfer-info">
                <div class="file-info">
                  <el-icon :size="20" class="file-icon"><component :is="getFileIcon(transfer.originalName)" /></el-icon>
                  <div class="file-details">
                    <div class="file-name" :title="transfer.originalName">{{ transfer.originalName }}</div>
                    <div class="file-size">{{ formatFileSize(transfer.fileSize) }}</div>
                  </div>
                </div>
                <div class="progress-info">
                  <el-progress
                    :percentage="Number(transfer.progressPercentage)"
                    :status="getProgressStatus(transfer.transferStatus)"
                    :stroke-width="4"
                  />
                  <div class="transfer-stats">
                    <span class="transferred">{{ formatFileSize(transfer.transferredBytes) }} / {{ formatFileSize(transfer.fileSize) }}</span>
                    <span class="speed">
                      <span v-if="transfer.transferSpeed > 0">{{ formatSpeed(transfer.transferSpeed) }}</span>
                      <span v-else-if="transfer.transferStatus === 'IN_PROGRESS' || transfer.transferStatus === 'PENDING'">传输中</span>
                      <span v-else>{{ getStatusText(transfer.transferStatus) }}</span>
                    </span>
                  </div>
                </div>
              </div>
              <div class="transfer-actions">
                <el-button-group size="small">
                  <el-button @click="pauseTransfer(transfer.id)" v-if="transfer.transferStatus === 'IN_PROGRESS'">{{ t('transfer.current.pause') }}</el-button>
                  <el-button @click="resumeTransfer(transfer.id)" v-if="transfer.transferStatus === 'PAUSED'">{{ t('transfer.current.resume') }}</el-button>
                  <el-button type="danger" @click="cancelTransfer(transfer.id)">{{ t('transfer.current.cancel') }}</el-button>
                </el-button-group>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 传输历史 -->
      <div v-if="viewMode === 'history'" class="card-grid-wrapper">
        <div class="history-controls">
          <el-select v-model="historyFilter" @change="handleFilterChange" style="width: 120px;">
            <el-option :label="t('transfer.history.filter_all')" value="all" />
            <el-option :label="t('transfer.history.filter_completed')" value="COMPLETED" />
            <el-option :label="t('transfer.history.filter_failed')" value="FAILED" />
          </el-select>
        </div>
        <div v-if="transferHistory.length === 0" class="empty-state">
          <el-empty :description="t('transfer.history.empty')" />
        </div>
        <div class="transfer-list" v-else>
           <div v-for="transfer in transferHistory" :key="transfer.id" class="transfer-item" :class="getStatusClass(transfer.transferStatus)">
            <div class="transfer-info">
              <div class="file-info">
                <el-icon :size="20" class="file-icon"><component :is="getFileIcon(transfer.originalName)" /></el-icon>
                <div class="file-details">
                  <div class="file-name" :title="transfer.originalName">{{ transfer.originalName }}</div>
                  <div class="file-size">{{ formatFileSize(transfer.fileSize) }}</div>
                </div>
              </div>
              <div class="history-info">
                <div class="history-meta">
                  <span>{{ t('transfer.history.table.completedAt') }}: {{ formatDateTime(transfer.createdAt) }}</span>
                </div>
                <div class="status-info">
                  <el-tooltip v-if="transfer.transferStatus === 'FAILED' && transfer.errorMessage" :content="transfer.errorMessage" placement="top">
                    <el-tag :type="getStatusTagType(transfer.transferStatus)" class="status-tag">{{ getStatusText(transfer.transferStatus) }}</el-tag>
                  </el-tooltip>
                  <el-tag v-else :type="getStatusTagType(transfer.transferStatus)" class="status-tag">{{ getStatusText(transfer.transferStatus) }}</el-tag>
                </div>
              </div>
            </div>
            <div class="transfer-actions">
               <el-button-group size="small">
                <el-button type="primary" @click="retryTransfer(transfer.id)" v-if="transfer.transferStatus === 'FAILED'">{{ t('transfer.history.retry') }}</el-button>
                <el-button type="danger" @click="deleteHistoryItem(transfer.id)">{{ t('transfer.history.delete') }}</el-button>
              </el-button-group>
            </div>
          </div>
        </div>
         <div class="pagination">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalRecords"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox, ElSegmented } from 'element-plus'
import {
  Refresh,
  Document,
  UploadFilled,
  CircleCheckFilled,
  CircleCloseFilled,
  Histogram,
  Picture as IconPicture,
  VideoPlay as IconVideo,
  Headset as IconAudio,
  Files as IconZip,
  Folder as IconFolder,
  VideoPlay,
  VideoPause,
  RefreshRight,
  Delete
} from '@element-plus/icons-vue'
import { useTransferStore } from '@/stores/transfer'
import { useUserStore } from '@/stores/user'
import { useAuthStore } from '@/stores/auth'
import { useFileUpload } from '@/composables/useFileUpload'
import { useFileDownload } from '@/composables/useFileDownload'

// Hooks
const { t } = useI18n()
const transferStore = useTransferStore()
const userStore = useUserStore()
const fileUpload = useFileUpload()
const fileDownload = useFileDownload()

// State
const viewMode = ref('current')
const historyFilter = ref('all')

const viewOptions = computed(() => [
  { label: t('transfer.current.title'), value: 'current' },
  { label: t('transfer.history.title'), value: 'history' }
])

// Computed properties from store
const isConnected = computed(() => transferStore.isConnected)
const connectionState = computed(() => transferStore.connectionState)
const reconnectAttempts = computed(() => transferStore.reconnectAttempts)
const showConnectionWarning = computed(() => transferStore.showConnectionWarning)
const activeTransfers = computed(() => transferStore.activeTransfers)
const transferHistory = computed(() => transferStore.transferHistory)
const statistics = computed(() => transferStore.statistics)
const currentPage = computed(() => transferStore.currentPage)
const pageSize = computed(() => transferStore.pageSize)
const totalRecords = computed(() => transferStore.totalRecords)
const isLoading = computed(() => transferStore.isLoading)

// Upload and Download sessions
const uploadSessions = computed(() => fileUpload.getAllSessions())
const uploadStats = computed(() => fileUpload.getUploadStats())
const downloadSessions = computed(() => fileDownload.getAllSessions())
const downloadStats = computed(() => fileDownload.getDownloadStats())

// Lifecycle hooks
onMounted(() => {
  if (transferStore.isConnected) {
    transferStore.loadTransferHistory()
  } else {
    reconnectSocket()
  }
})

watch(isConnected, (connected) => {
  if (connected) {
    transferStore.loadTransferHistory()
  }
})

watch(viewMode, (newMode) => {
  if (newMode === 'history' && transferHistory.value.length === 0) {
    transferStore.loadTransferHistory()
  }
})

// Utility Functions
const getFileIcon = (fileName: string) => {
  if (!fileName) return Document
  const extension = fileName.split('.').pop()?.toLowerCase()
  if (!extension) return Document

  const imageExts = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg']
  const videoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv']
  const audioExts = ['mp3', 'wav', 'ogg', 'flac']
  const zipExts = ['zip', 'rar', '7z', 'gz', 'tar']

  if (imageExts.includes(extension)) return IconPicture
  if (videoExts.includes(extension)) return IconVideo
  if (audioExts.includes(extension)) return IconAudio
  if (zipExts.includes(extension)) return IconZip
  
  return Document
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
}

const formatSpeed = (bytesPerSecond: number): string => {
  return `${formatFileSize(bytesPerSecond)}/s`
}

const formatDateTime = (dateTime: string): string => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

const getProgressStatus = (status: string) => {
  switch (status) {
    case 'COMPLETED': return 'success'
    case 'FAILED': return 'exception'
    case 'PAUSED': return 'warning'
    default: return undefined
  }
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'COMPLETED': return 'success'
    case 'FAILED': return 'danger'
    case 'PAUSED': return 'warning'
    case 'IN_PROGRESS': return 'primary'
    default: return 'info'
  }
}

const getStatusClass = (status: string) => {
  switch (status) {
    case 'IN_PROGRESS': return 'status-in-progress'
    case 'COMPLETED': return 'status-completed'
    case 'FAILED': return 'status-failed'
    case 'PAUSED': return 'status-paused'
    case 'CANCELLED': return 'status-cancelled'
    default: return 'status-pending'
  }
}

const getStatusText = (status: string): string => {
  return t(`transfer.status.${status}`, status)
}

// 上传状态相关方法
const getUploadStatusClass = (status: string) => {
  switch (status) {
    case 'uploading': return 'status-in-progress'
    case 'completed': return 'status-completed'
    case 'failed': return 'status-failed'
    case 'paused': return 'status-paused'
    case 'cancelled': return 'status-cancelled'
    default: return 'status-pending'
  }
}

const getUploadProgressStatus = (status: string) => {
  switch (status) {
    case 'completed': return 'success'
    case 'failed': return 'exception'
    case 'paused': return 'warning'
    default: return undefined
  }
}

const getUploadStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'preparing': '准备中',
    'uploading': '上传中',
    'paused': '已暂停',
    'completed': '已完成',
    'failed': '上传失败',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 下载状态相关方法
const getDownloadStatusClass = (status: string) => {
  switch (status) {
    case 'downloading': return 'status-in-progress'
    case 'completed': return 'status-completed'
    case 'failed': return 'status-failed'
    case 'paused': return 'status-paused'
    case 'cancelled': return 'status-cancelled'
    default: return 'status-pending'
  }
}

const getDownloadProgressStatus = (status: string) => {
  switch (status) {
    case 'completed': return 'success'
    case 'failed': return 'exception'
    case 'paused': return 'warning'
    default: return undefined
  }
}

const getDownloadStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'idle': '空闲',
    'preparing': '准备中',
    'downloading': '下载中',
    'paused': '已暂停',
    'completed': '已完成',
    'failed': '下载失败',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// Event Handlers
const refreshTransfers = () => {
  window.location.reload()
}

const handleFilterChange = () => {
  transferStore.loadTransferHistory(0, pageSize.value, historyFilter.value)
}

const clearHistory = async () => {
  try {
    await ElMessageBox.confirm(
      t('transfer.transferDialogs.clear_text'),
      t('transfer.transferDialogs.clear_title'),
      { type: 'warning' }
    )
    await transferStore.clearTransferHistory()
    ElMessage.success(t('transfer.messages.history_cleared'))
  } catch {
    // User cancelled
  }
}

const cancelTransfer = async (transferId: number) => {
  const transfer = activeTransfers.value.find(t => t.id === transferId)
  if (!transfer) return;
  try {
    await ElMessageBox.confirm(
      t('transfer.transferDialogs.cancel_text', { name: transfer.originalName }),
      t('transfer.transferDialogs.cancel_title'),
      { type: 'warning' }
    )
    // 调用取消传输功能
    await cancelTransferById(transferId)
  } catch {
    // User cancelled
  }
}

const pauseTransfer = (transferId: number) => {
  ElMessage.info(t('transfer.messages.pause_wip'))
  const transfer = activeTransfers.value.find(t => t.id === transferId)
  if (transfer) transfer.transferStatus = 'PAUSED'
}

const resumeTransfer = (transferId: number) => {
  ElMessage.info(t('transfer.messages.resume_wip'))
  const transfer = activeTransfers.value.find(t => t.id === transferId)
  if (transfer) transfer.transferStatus = 'IN_PROGRESS'
}

const deleteHistoryItem = async (transferId: number) => {
   const transfer = transferHistory.value.find(t => t.id === transferId)
   if (!transfer) return;
    try {
      await ElMessageBox.confirm(
        t('transfer.transferDialogs.delete_text', { name: transfer.originalName }),
        t('transfer.transferDialogs.delete_title'),
        { type: 'warning' }
      )
      // await transferStore.deleteHistoryItem(transferId) // Uncomment when implemented
      ElMessage.success(t('transfer.messages.delete_ok'))
  } catch {
    // User cancelled
  }
}

const retryTransfer = (transferId: number) => {
  ElMessage.info(t('transfer.messages.retry_wip'))
}

// 取消传输功能
const cancelTransferById = async (transferId: number) => {
  try {
    // 查找对应的传输记录
    const transfer = activeTransfers.value.find(t => t.id === transferId)
    if (!transfer) {
      ElMessage.error('传输记录不存在')
      return
    }

    // 如果是文件上传会话，调用文件上传的取消功能
    const uploadSession = fileUpload.getAllSessions().find(s =>
      s.transferRecordId === transferId || s.fileName === transfer.originalName
    )

    if (uploadSession) {
      // 取消文件上传会话（这会调用后端API删除数据库记录）
      await fileUpload.cancelUpload(uploadSession.uploadId)
      ElMessage.success(`已取消上传: ${transfer.originalName}`)
    } else {
      // 直接调用后端API删除传输记录
      await transferStore.deleteTransferRecord(transferId)
      ElMessage.success(`已取消传输: ${transfer.originalName}`)
    }

    // 刷新传输列表（删除操作已经在deleteTransferRecord中更新了状态，无需额外刷新）

  } catch (error) {
    console.error('取消传输失败:', error)
    ElMessage.error('取消传输失败')
  }
}

// 上传会话控制函数
const pauseUploadSession = (sessionId: string) => {
  fileUpload.pauseUpload(sessionId)
}

const resumeUploadSession = (sessionId: string) => {
  fileUpload.resumeUpload(sessionId)
}

const retryUploadSession = (sessionId: string) => {
  fileUpload.retryUpload(sessionId)
}

const cancelUploadSession = (sessionId: string) => {
  fileUpload.cancelUpload(sessionId)
}

// 下载会话控制函数
const pauseDownloadSession = (sessionId: string) => {
  fileDownload.pauseDownload(sessionId)
}

const resumeDownloadSession = (sessionId: string) => {
  fileDownload.resumeDownload(sessionId)
}

const retryDownloadSession = (sessionId: string) => {
  // 重试下载：重新开始下载
  const session = downloadSessions.value.find(s => s.downloadId === sessionId)
  if (session) {
    fileDownload.downloadFileWithProgress(session.fileId, session.fileName, session.fileSize)
  }
}

const cancelDownloadSession = (sessionId: string) => {
  fileDownload.cancelDownload(sessionId)
}

const reconnectSocket = async () => {
  try {
    // 使用authStore替代userStore，与全局连接保持一致
    const authStore = useAuthStore()

    // 检查认证状态，与DashboardLayout.vue保持一致
    if (!authStore.isAuthenticated) {
      console.warn('⚠️ 用户未登录，跳过Socket重连')
      return
    }

    const userId = authStore.user?.id
    if (userId) {
      await transferStore.reconnectSocket(userId)
    } else {
      console.warn('⚠️ 无法获取用户ID，跳过Socket重连')
    }
  } catch (error) {
    console.error('Socket重连失败:', error)
  }
}

const handleSizeChange = (size: number) => {
  transferStore.handleSizeChange(size, historyFilter.value)
}

const handleCurrentChange = (page: number) => {
  transferStore.handlePageChange(page, historyFilter.value)
}
</script>

<style scoped lang="scss">
.transfer-list-v3 {
  padding: 24px;
  background-color: var(--bg-color-primary);
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    h2 {
      margin: 0;
      color: var(--text-color-primary);
      font-size: 24px;
      font-weight: 600;
    }
  }
  
  .transfer-stats {
    margin-bottom: 24px;
    .stat-card {
      border: none;
      background-color: var(--bg-color-secondary);
      .stat-item {
        display: flex;
        align-items: center;
        gap: 16px;
        .stat-icon { font-size: 32px; }
        .stat-content {
          text-align: left;
          .stat-value {
            font-size: 22px;
            font-weight: bold;
            color: var(--text-color-primary);
          }
          .stat-label {
            font-size: 13px;
            color: var(--text-color-secondary);
          }
        }
      }
    }
  }
  
  .connection-status { margin-bottom: 24px; }

  .view-switcher {
    margin-bottom: 24px;
    display: flex;
    justify-content: center;
  }

  .history-controls {
    margin-bottom: 16px;
  }

  .card-grid-wrapper {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .transfer-list {
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    overflow: hidden;
  }

  .transfer-item {
    background-color: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-light);
    padding: 12px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    min-height: 60px;
    transition: background-color 0.2s ease-in-out;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    // 状态指示器（左边框）
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 4px;
      background-color: var(--el-color-info);
    }

    &.status-in-progress::before { background-color: var(--el-color-primary); }
    &.status-completed::before { background-color: var(--el-color-success); }
    &.status-failed::before { background-color: var(--el-color-error); }
    &.status-paused::before { background-color: var(--el-color-warning); }
    &.status-cancelled::before { background-color: var(--el-color-info-light-3); }

    // 上传会话状态
    &.status-uploading::before { background-color: var(--el-color-primary); }
    &.status-preparing::before { background-color: var(--el-color-info); }
    
    .transfer-info {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 20px;
      min-width: 0;
    }

    .file-info {
      display: flex;
      align-items: center;
      gap: 12px;
      min-width: 200px;
      flex-shrink: 0;

      .file-icon {
        color: var(--el-color-primary);
        flex-shrink: 0;
      }

      .file-details {
        flex: 1;
        min-width: 0;

        .file-name {
          font-weight: 500;
          color: var(--el-text-color-primary);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 14px;
          line-height: 1.4;
        }

        .file-size {
          font-size: 11px;
          color: var(--el-text-color-regular);
          margin-top: 2px;
        }
      }
    }

    .progress-info {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 16px;
      min-width: 300px;

      .el-progress {
        flex: 1;
        min-width: 120px;
      }

      .transfer-stats {
        display: flex;
        gap: 12px;
        font-size: 11px;
        color: var(--el-text-color-regular);
        white-space: nowrap;

        .transferred, .speed, .chunks {
          white-space: nowrap;
        }
      }
    }

    .history-info {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 16px;

      .history-meta {
        font-size: 11px;
        color: var(--el-text-color-regular);
        white-space: nowrap;
      }

      .status-info {
        .status-tag {
          font-size: 11px;
          padding: 2px 8px;
        }
      }
    }

    .transfer-actions {
      flex-shrink: 0;
      margin-left: 12px;

      .el-button-group .el-button {
        padding: 4px 8px;
        font-size: 11px;
      }
    }
  }

  .empty-state {
    padding: 40px 0;
    grid-column: 1 / -1;
  }

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-color-primary);
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 2px solid var(--border-color-light);
  }

  .upload-sessions-section,
  .socket-transfers-section {
    margin-bottom: 24px;
  }
}
</style>
